package tld.course.homework1 
{
	/**
	 * ...
	 * @author wvxvw
	 */
	public class Computer
	{
		private static const WINS:Vector.<uint> =
			new <uint>[
				0, 1, 2, 
				3, 4, 5, 
				6, 7, 8,
				0, 3, 6, 
				1, 4, 7, 
				2, 5, 8,
				0, 4, 8, 
				2, 4, 6
			];
		
		private const _choices:Vector.<uint> = new Vector.<uint>(9);
		private var _hasChoice:Boolean;
		
		public function Computer() { super(); }
		
		public function makeTurn(grid:Grid):void
		{
			var max:uint;
			
			this._choices.splice(0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0);
			this._hasChoice = false;
			this.findPossibleWins(grid);
			if (!this._hasChoice) this.findPossibleMoves(grid);
			if (this._hasChoice)
			{
				for (var i:int; i < 9; i++) 
					max = Math.max(max, this._choices[i]);
				grid.setItem(this._choices.indexOf(max), "o");
			}
		}
		
		private function findPossibleWins(grid:Grid):void
		{
			var first:String;
			var second:String;
			var third:String;
			
			for (var i:int; i < WINS.length; i += 3)
			{
				first = grid.getItem(WINS[i]);
				second = grid.getItem(WINS[i + 1]);
				third = grid.getItem(WINS[i + 2]);
				if (first && first == second && !third)
					this.addChoice(WINS[i + 2]);
				else if (first && first == third && !second)
					this.addChoice(WINS[i + 1]);
				else if (second && second == third && !first)
					this.addChoice(WINS[i]);
			}
		}
		
		private function findPossibleMoves(grid:Grid):void
		{
			var first:String;
			var second:String;
			var third:String;
			
			for (var i:int; i < WINS.length; i += 3)
			{
				first = grid.getItem(WINS[i]);
				second = grid.getItem(WINS[i + 1]);
				third = grid.getItem(WINS[i + 2]);
				if (first && !(second + third))
				{
					this.addChoice(WINS[i + 1]);
					this.addChoice(WINS[i + 2]);
				}
				else if (third && !(first + second))
				{
					this.addChoice(WINS[i + 1]);
					this.addChoice(WINS[i]);
				}
				else if (second && !(first + third))
				{
					this.addChoice(WINS[i + 2]);
					this.addChoice(WINS[i]);
				}
				else if (!(first + second + third))
				{
					this.addChoice(WINS[i + 2]);
					this.addChoice(WINS[i + 1]);
					this.addChoice(WINS[i]);
				}
			}
		}
		
		private function addChoice(choice:uint):void
		{
			this._choices[choice]++;
			this._hasChoice = true;
		}
	}
}